<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频管理系统</title>
    <!-- Bootstrap CSS -->
    <link th:href="@{/css/bootstrap.css}" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Simple DataTables CSS -->
    <link th:href="@{/css/tables.css}" rel="stylesheet">

    <style>
        /* 添加以下CSS样式 */
        .toggle-password {
            border-top-left-radius: 0;
            border-bottom-left-radius: 0;
        }

        .toast {
            min-width: 300px;
        }

        /* 密码强度指示器 */
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 2px;
            transition: all 0.3s ease;
        }

        .password-strength.weak {
            background-color: #e74c3c;
            width: 33%;
        }

        .password-strength.medium {
            background-color: #f39c12;
            width: 66%;
        }

        .password-strength.strong {
            background-color: #27ae60;
            width: 100%;
        }
    </style>
    <style>
        .url-link {
            color: #3498db;
            text-decoration: none;
            font-weight: 500;
            display: inline-block;
            max-width: 200px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            transition: all 0.2s ease;
        }

        .url-link:hover {
            color: #2980b9;
            text-decoration: underline;
        }

        .table a {
            color: #3498db;
            text-decoration: none;
            font-weight: 500;
            padding: 4px 8px;
            border-radius: 4px;
            background-color: rgba(52, 152, 219, 0.1);
            transition: all 0.2s ease;
        }

        .table a:hover {
            background-color: rgba(52, 152, 219, 0.2);
            text-decoration: underline;
        }

        /* 基础样式 */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            overflow-x: hidden;
            color: #333;
            background-color: #f8f9fa;
        }

        .sidebar {
            min-height: 100vh;
            background-color: #2c3e50;
            color: white;
            transition: all 0.3s ease;
            box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
        }

        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 0.8rem 1.5rem;
            transition: all 0.3s ease;
            border-left: 3px solid transparent;
        }

        .sidebar .nav-link:hover {
            color: white;
            background-color: rgba(255, 255, 255, 0.1);
        }

        .sidebar .nav-link.active {
            color: white;
            background-color: #3498db;
            border-left: 3px solid #2980b9;
        }

        .sidebar .nav-link i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        .content {
            transition: all 0.3s ease;
            padding: 2rem;
        }

        .page-title {
            margin-bottom: 1.5rem;
            color: #2c3e50;
            font-weight: 600;
            position: relative;
            padding-bottom: 0.5rem;
        }

        .page-title::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 50px;
            height: 3px;
            background-color: #3498db;
        }

        /* 卡片样式 */
        .card {
            border: none;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .card:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
        }

        .card-header {
            background-color: white;
            border-bottom: 1px solid #f1f1f1;
            font-weight: 500;
            color: #2c3e50;
        }

        /* 按钮样式 */
        .btn {
            transition: all 0.2s ease;
            border-radius: 4px;
        }

        .btn-primary {
            background-color: #3498db;
            border-color: #3498db;
        }

        .btn-primary:hover {
            background-color: #2980b9;
            border-color: #2980b9;
        }

        .btn-danger {
            background-color: #e74c3c;
            border-color: #e74c3c;
        }

        .btn-danger:hover {
            background-color: #c0392b;
            border-color: #c0392b;
        }

        .btn-outline-secondary {
            transition: all 0.2s ease;
        }

        .btn-outline-secondary:hover {
            background-color: #6c757d;
            color: white;
        }

        /* 表格样式 */
        table.dataTable {
            border-collapse: separate;
            border-spacing: 0;
        }

        table.dataTable thead th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #e9ecef;
            font-weight: 600;
            color: #495057;
        }

        table.dataTable tbody tr {
            transition: background-color 0.2s ease;
        }

        table.dataTable tbody tr:hover {
            background-color: rgba(52, 152, 219, 0.05);
        }

        /* 表单样式 */
        .form-control {
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
            border-radius: 4px;
        }

        .form-control:focus {
            border-color: #3498db;
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.25);
        }

        /* 模态框样式 */
        .modal-content {
            border-radius: 8px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            animation: modalFadeIn 0.3s ease;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            border-bottom: 1px solid #f1f1f1;
        }

        .modal-title {
            color: #2c3e50;
            font-weight: 600;
        }

        /* 操作按钮组 */
        .action-buttons .btn {
            margin-right: 5px;
            padding: 3px 10px;
            font-size: 0.875rem;
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .sidebar {
                position: fixed;
                z-index: 100;
                width: 250px;
                transform: translateX(-100%);
            }

            .sidebar.show {
                transform: translateX(0);
            }

            .content {
                padding: 1rem;
            }

            .mobile-menu-toggle {
                display: block !important;
            }
        }

        .mobile-menu-toggle {
            display: none;
            position: fixed;
            top: 15px;
            left: 15px;
            z-index: 101;
            background-color: #2c3e50;
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            align-items: center;
            justify-content: center;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        /* 加载状态 */
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(52, 152, 219, 0.3);
            border-radius: 50%;
            border-top-color: #3498db;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        /* 教育相关装饰元素 */
        .education-decoration {
            position: absolute;
            opacity: 0.03;
            z-index: -1;
            font-size: 200px;
            color: #3498db;
            right: -50px;
            bottom: -100px;
        }
    </style>
</head>
<body>
<!-- 移动端菜单按钮 -->
<button class="mobile-menu-toggle d-flex align-items-center justify-content-center">
    <i class="fas fa-bars"></i>
</button>

<div class="container-fluid p-0">
    <div class="row g-0">
        <!-- 左侧导航栏 -->
        <div class="col-md-3 col-lg-2 sidebar">
            <div class="p-3 mb-4 border-bottom border-light">
                <h4 class="text-white mb-0"><i class="fas fa-graduation-cap me-2"></i>视频管理系统</h4>
            </div>
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link active" id="title-link" href="#title-page">
                        <i class="fas fa-heading"></i>标题管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="category1-link" href="#category1-page">
                        <i class="fas fa-folder"></i>一级分类管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="category2-link" href="#category2-page">
                        <i class="fas fa-folder-open"></i>二级分类管理
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" id="video-link" href="#video-page">
                        <i class="fas fa-video"></i>视频管理
                    </a>
                </li>
            </ul>
        </div>

        <!-- 主内容区域 -->
        <div class="col-md-9 ms-sm-auto col-lg-10 px-md-4 content">
            <!-- 标题管理页面 -->
            <div id="title-page" class="page-content active">
                <h2 class="page-title">标题管理</h2>
                <div class="card">
                    <div class="card-body p-4">
                        <form id="title-form" th:action="@{/admin/video/edit}" method="post">
                            <div class="mb-3">
                                <label for="site-title" class="form-label">网站标题</label>
                                <input type="text" class="form-control" id="site-title" name="title"
                                       th:value="${title}" placeholder="请输入网站标题">
                            </div>
                            <button type="button" id="save-title" class="btn btn-primary">
                                <i class="fas fa-save me-1"></i>保存
                            </button>
                        </form>
                    </div>

                    <div class="text-center mb-5">
                        <a href="/" class="btn btn-outline-primary me-2">
                            <i class="fa fa-home mr-1"></i>返回前台
                        </a>
                        <button type="button" class="btn btn-outline-warning me-2" data-bs-toggle="modal"
                                data-bs-target="#changePasswordModal">
                            <i class="fa fa-key mr-1"></i>修改密码
                        </button>
                        <a href="/logout" class="btn btn-outline-danger">
                            <i class="fa fa-sign-out-alt mr-1"></i>退出登录
                        </a>
                    </div>
                </div>
            </div>

            <!-- 一级分类管理页面 -->
            <div id="category1-page" class="page-content d-none">
                <h2 class="page-title">一级分类管理</h2>
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>一级分类列表</span>
                        <button type="button" class="btn btn-primary btn-sm" id="add-category1">
                            <i class="fas fa-plus me-1"></i>新增
                        </button>
                    </div>
                    <div class="card-body">
                        <table id="category1-table" class="table table-striped">
                            <thead>
                            <tr>
                                <th>编号</th>
                                <th>分类名称</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="category : ${categories}">
                                <td th:text="${category.id}"></td>
                                <td th:text="${category.name}"></td>
                                <td class="action-buttons">
                                    <button type="button" class="btn btn-outline-secondary btn-sm edit-category1"
                                            th:data-id="${category.id}" th:data-name="${category.name}">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm delete-category1"
                                            th:data-id="${category.id}">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 二级分类管理页面 -->
            <div id="category2-page" class="page-content d-none">
                <h2 class="page-title">二级分类管理</h2>
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>二级分类列表</span>
                        <button type="button" class="btn btn-primary btn-sm" id="add-category2">
                            <i class="fas fa-plus me-1"></i>新增
                        </button>
                    </div>
                    <div class="card-body">
                        <table id="category2-table" class="table table-striped">
                            <thead>
                            <tr>
                                <th>编号</th>
                                <th>分类名称</th>
                                <th>所属一级分类</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="subcategory : ${subcategories}">
                                <td th:text="${subcategory.id}"></td>
                                <td th:text="${subcategory.name}"></td>
                                <td th:text="${subcategory.categoryName}"></td>
                                <td class="action-buttons">
                                    <button type="button" class="btn btn-outline-secondary btn-sm edit-category2"
                                            th:data-id="${subcategory.id}"
                                            th:data-name="${subcategory.name}"
                                            th:data-category-id="${subcategory.categoryId}">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm delete-category2"
                                            th:data-id="${subcategory.id}">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 视频管理页面 -->
            <div id="video-page" class="page-content d-none">
                <h2 class="page-title">视频管理</h2>
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <span>视频列表</span>
                        <button type="button" class="btn btn-primary btn-sm" id="add-video">
                            <i class="fas fa-plus me-1"></i>新增
                        </button>
                    </div>
                    <div class="card-body">
                        <table id="video-table" class="table table-striped">
                            <thead>
                            <tr>
                                <th>编号</th>
                                <th>标题</th>
                                <th>链接</th>
                                <th>所属二级分类</th>
                                <th>所属一级分类</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="video : ${videos}">
                                <td th:text="${video.videoId}"></td>
                                <td th:text="${video.title}"></td>
                                <td>
                                    <!-- 如果 video.url 是 HTTP(S) 链接，则直接创建一个普通链接 -->
                                    <th:block th:if="${#strings.startsWith(video.url, 'http')}">
                                        <a href="#" th:href="@{${video.url}}" target="_blank" class="url-link"
                                           th:attr="title=${video.url}">
                                            <!-- 添加链接文本显示，超过20字符显示... -->
                                            <span th:text="${#strings.length(video.url) > 20 ? #strings.substring(video.url, 0, 20) + '...' : video.url}"></span>
                                        </a>
                                    </th:block>

                                    <!-- 否则，创建指向播放页面的链接 -->
                                    <th:block th:unless="${#strings.startsWith(video.url, 'http')}">
                                        <a th:href="@{/playVideo(videoUrl=${video.url})}" class="url-link"
                                           th:attr="title=${video.url}">
                                            <!-- 添加链接文本显示，超过20字符显示... -->
                                            <span th:text="${#strings.length(video.url) > 20 ? #strings.substring(video.url, 0, 20) + '...' : video.url}"></span>
                                        </a>
                                    </th:block>
                                </td>
                                <td th:text="${video.twoName}"></td>
                                <td th:text="${video.oneName}"></td>
                                <td class="action-buttons">
                                    <button type="button" class="btn btn-outline-secondary btn-sm edit-video"
                                            th:data-id="${video.videoId}"
                                            th:data-title="${video.title}"
                                            th:data-url="${video.url}"
                                            th:data-subcategory-id="${video.subcategoryId}">
                                        <i class="fas fa-edit me-1"></i>编辑
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm delete-video"
                                            th:data-id="${video.videoId}">
                                        <i class="fas fa-trash me-1"></i>删除
                                    </button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 教育相关装饰元素 -->
            <div class="education-decoration">
                <i class="fas fa-book"></i>
            </div>
        </div>
    </div>
</div>

<!-- 标题修改确认弹窗 -->
<div class="modal fade" id="confirm-title-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认修改</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>确定要修改网站标题吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-title-save">确认保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 一级分类模态框 -->
<div class="modal fade" id="category1-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="category1-modal-title">新增一级分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="category1-form" th:action="@{/admin/video/addOne}" method="post">
                <input type="hidden" id="category1-id" name="id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="category1-name" class="form-label">分类名称</label>
                        <input type="text" class="form-control" id="category1-name" name="name" required
                               placeholder="请输入一级分类名称">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <span id="category1-save-text">保存</span>
                        <span id="category1-loading" class="loading d-none ms-2"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 二级分类模态框 -->
<div class="modal fade" id="category2-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="category2-modal-title">新增二级分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="category2-form" th:action="@{/admin/video/addTwo}" method="post">
                <input type="hidden" id="category2-id" name="id">
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="category2-name" class="form-label">分类名称</label>
                        <input type="text" class="form-control" id="category2-name" name="name" required
                               placeholder="请输入二级分类名称">
                    </div>
                    <div class="mb-3">
                        <label for="category2-parent" class="form-label">所属一级分类</label>
                        <select class="form-select" id="category2-parent" name="categoryId" required>
                            <option value="">请选择一级分类</option>
                            <option th:each="category : ${categories}"
                                    th:value="${category.id}"
                                    th:text="${category.name}"></option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <span id="category2-save-text">保存</span>
                        <span id="category2-loading" class="loading d-none ms-2"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<!-- 视频模态框 -->
<div class="modal fade" id="video-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="video-modal-title">新增视频</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="video-form" enctype="multipart/form-data" method="post">
                <input type="hidden" id="video-id" name="videoId">
                <input type="hidden" id="video-upload-mode" name="uploadMode" value="network">
                <input type="hidden" id="video-storage-name" name="storageName">
                <div class="modal-body">
                    <div class="row g-3">
                        <!-- 上传模式选择 -->
                        <div class="col-md-12">
                            <label class="form-label">上传模式</label>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="uploadModeRadio" id="mode-network"
                                       value="network" checked>
                                <label class="form-check-label" for="mode-network">网络视频</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="uploadModeRadio" id="mode-local"
                                       value="local">
                                <label class="form-check-label" for="mode-local">本地上传</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="uploadModeRadio" id="mode-server"
                                       value="server">
                                <label class="form-check-label" for="mode-server">服务器复制</label>
                            </div>
                        </div>

                        <div class="col-md-12">
                            <label for="video-title" class="form-label">标题</label>
                            <input type="text" class="form-control" id="video-title" name="title" required
                                   placeholder="请输入视频标题">
                        </div>

                        <!-- 网络视频和服务器复制模式下的链接输入 -->
                        <div class="col-md-12" id="video-url-container">
                            <label for="video-url" class="form-label">链接</label>
                            <input type="text" class="form-control" id="video-url" name="url"
                                   placeholder="请输入视频链接">
                        </div>

                        <!-- 本地上传模式下的文件选择 -->
                        <div class="col-md-12" id="video-file-container" style="display: none;">
                            <label for="video-file" class="form-label">视频文件</label>
                            <input class="form-control" type="file" id="video-file" name="videoFile" accept="video/*">
                            <div class="progress mt-2" id="video-upload-progress" style="display: none;">
                                <div class="progress-bar" role="progressbar" style="width: 0;" aria-valuenow="0"
                                     aria-valuemin="0" aria-valuemax="100">0%
                                </div>
                            </div>
                            <div id="video-upload-status" class="form-text"></div>
                        </div>

                        <div class="col-md-6">
                            <label for="video-category1" class="form-label">所属一级分类</label>
                            <select class="form-select" id="video-category1" name="category1Id" required>
                                <option value="">请选择一级分类</option>
                                <option th:each="category : ${categories}"
                                        th:value="${category.id}"
                                        th:text="${category.name}"></option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label for="video-category2" class="form-label">所属二级分类</label>
                            <select class="form-select" id="video-category2" name="subcategoryId" required>
                                <option value="">请先选择一级分类</option>
                            </select>
                        </div>
                        <div class="col-md-12">
                            <label for="video-image" class="form-label">封面图片</label>
                            <input class="form-control" type="file" id="video-image" name="file" accept="image/*">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary" id="video-submit-btn">
                        <span id="video-save-text">保存</span>
                        <span id="video-loading" class="loading d-none ms-2"></span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="delete-confirm-modal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p id="delete-confirm-text">确定要删除吗？</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirm-delete">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改密码模态框 -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">修改密码</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 修正action路径，使用Thymeleaf语法 -->
                <form id="changePasswordForm" th:action="@{/admin/change-password}" method="post">
                    <div class="mb-3">
                        <label for="currentPassword" class="form-label">当前密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="currentPassword" name="currentPassword"
                                   required>
                            <button type="button" class="btn btn-outline-secondary toggle-password"
                                    data-target="currentPassword">
                                <i class="fa fa-eye"></i>
                            </button>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="newPassword" class="form-label">新密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="newPassword" name="newPassword" required
                                   minlength="6">
                            <button type="button" class="btn btn-outline-secondary toggle-password"
                                    data-target="newPassword">
                                <i class="fa fa-eye"></i>
                            </button>
                        </div>
                        <div class="form-text">密码长度至少6位</div>
                    </div>
                    <div class="mb-3">
                        <label for="confirmPassword" class="form-label">确认新密码</label>
                        <div class="input-group">
                            <input type="password" class="form-control" id="confirmPassword" required>
                            <button type="button" class="btn btn-outline-secondary toggle-password"
                                    data-target="confirmPassword">
                                <i class="fa fa-eye"></i>
                            </button>
                        </div>
                        <div class="invalid-feedback" id="confirmPasswordError">两次输入的密码不一致</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="submitChangePassword">确认修改</button>
            </div>
        </div>
    </div>
</div>
<!-- Bootstrap JS -->
<script th:src="@{/js/bootstrap.js}"></script>
<script th:src="@{/js/jQuery.js}"></script>
<script th:src="@{/js/tables.js}"></script>
<script>
    // 全局变量
    let currentDeleteId = null;
    let currentDeleteType = null;
    let category1Data = [];
    let category2Data = [];
    // 视频系统专用 JavaScript 代码
    $(document).ready(function () {
        // 初始化数据
        initData();

        // 初始化表格
        initTables();

        // 初始化导航
        initNavigation();

        // 初始化事件监听
        initEventListeners();
    });

    // 初始化数据
    function initData() {
        // 从页面元素中提取分类数据
        category1Data = [];
        $('#category2-parent option').each(function () {
            if ($(this).val() !== '') {
                category1Data.push({
                    id: $(this).val(),
                    name: $(this).text()
                });
            }
        });

        // 从表格中提取二级分类数据
        category2Data = [];
        $('#category2-table tbody tr').each(function () {
            const id = $(this).find('td:first').text();
            const name = $(this).find('td:nth-child(2)').text();
            const categoryId = $(this).find('.edit-category2').data('category-id');

            if (id && name && categoryId) {
                category2Data.push({
                    id: id,
                    name: name,
                    categoryId: categoryId
                });
            }
        });
    }

    // 初始化表格
    function initTables() {
        // 一级分类表格
        new simpleDatatables.DataTable("#category1-table", {
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true
        });

        // 二级分类表格
        new simpleDatatables.DataTable("#category2-table", {
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true
        });

        new simpleDatatables.DataTable("#video-table", {
            "paging": true,
            "lengthChange": true,
            "searching": true,
            "ordering": true,
            "info": true
        });
    }

    // 初始化导航
    function initNavigation() {
        // 导航链接点击事件
        $('.nav-link').click(function (e) {
            e.preventDefault();

            // 移除所有激活状态
            $('.nav-link').removeClass('active');
            $('.page-content').addClass('d-none');

            // 添加当前激活状态
            $(this).addClass('active');

            // 显示对应页面
            const targetId = $(this).attr('href').substring(1);
            $('#' + targetId).removeClass('d-none');

            // 在移动设备上点击导航后隐藏侧边栏
            if ($(window).width() <= 768) {
                $('.sidebar').removeClass('show');
            }
        });

        // 移动端菜单切换
        $('.mobile-menu-toggle').click(function () {
            $('.sidebar').toggleClass('show');
        });
    }

    // 初始化事件监听
    function initEventListeners() {
        // 标题管理相关
        $('#save-title').click(function () {
            $('#confirm-title-modal').modal('show');
        });

        $('#confirm-title-save').click(function () {
            $('#title-form').submit();
        });

        // 一级分类相关
        $('#add-category1').click(function () {
            $('#category1-modal-title').text('新增一级分类');
            $('#category1-form').attr('action', '/admin/video/addOne');
            $('#category1-id').val('');
            $('#category1-name').val('').focus();
            $('#category1-modal').modal('show');
        });

        $('.edit-category1').click(function () {
            const id = $(this).data('id');
            const name = $(this).data('name');

            $('#category1-modal-title').text('编辑一级分类');
            $('#category1-form').attr('action', '/admin/video/updateOne');
            $('#category1-id').val(id);
            $('#category1-name').val(name).focus();
            $('#category1-modal').modal('show');
        });

        $('.delete-category1').click(function () {
            currentDeleteId = $(this).data('id');
            currentDeleteType = 'category1';
            $('#delete-confirm-text').text('确定要删除这个一级分类吗？如果该分类下有二级分类，将无法删除。');
            $('#delete-confirm-modal').modal('show');
        });

        // 二级分类相关
        $('#add-category2').click(function () {
            $('#category2-modal-title').text('新增二级分类');
            $('#category2-form').attr('action', '/admin/video/addTwo');
            $('#category2-id').val('');
            $('#category2-name').val('');
            $('#category2-parent').val('');
            $('#category2-modal').modal('show');
        });

        $('.edit-category2').click(function () {
            const id = $(this).data('id');
            const name = $(this).data('name');
            const categoryId = $(this).data('category-id');

            $('#category2-modal-title').text('编辑二级分类');
            $('#category2-form').attr('action', '/admin/video/updateTwo');
            $('#category2-id').val(id);
            $('#category2-name').val(name);
            $('#category2-parent').val(categoryId);
            $('#category2-modal').modal('show');
        });

        $('.delete-category2').click(function () {
            currentDeleteId = $(this).data('id');
            currentDeleteType = 'category2';
            $('#delete-confirm-text').text('确定要删除这个二级分类吗？如果该分类下有视频，将无法删除。');
            $('#delete-confirm-modal').modal('show');
        });

        // 视频相关 - 修改后的代码
        $('#add-video').click(function () {
            $('#video-modal-title').text('新增视频');
            $('#video-form').attr('action', '/admin/video/add');
            $('#video-id').val('');
            $('#video-title').val('');
            $('#video-url').val('');
            $('#video-category1').val('');
            $('#video-category2').html('<option value="">请先选择一级分类</option>');
            $('#video-storage-name').val('');
            $('#video-upload-mode').val('network');

            // 重置上传模式
            $('input[name="uploadModeRadio"][value="network"]').prop('checked', true);
            $('#video-url-container').show();
            $('#video-file-container').hide();
            $('#video-upload-progress').hide();
            $('#video-upload-status').text('');
            $('#video-submit-btn').prop('disabled', false);

            $('#video-modal').modal('show');
        });

        $('.edit-video').click(function () {
            const id = $(this).data('id');
            const title = $(this).data('title');
            const url = $(this).data('url');
            const subcategoryId = $(this).data('subcategory-id');
            const uploadMode = $(this).data('upload-mode') || 'network';

            // 查找对应的二级分类
            const subcategory = category2Data.find(item => item.id == subcategoryId);

            $('#video-modal-title').text('编辑视频');
            $('#video-form').attr('action', '/admin/video/update/' + id);
            $('#video-id').val(id);
            $('#video-title').val(title);
            $('#video-upload-mode').val(uploadMode);

            // 设置上传模式
            $('input[name="uploadModeRadio"][value="' + uploadMode + '"]').prop('checked', true);
            updateUploadModeDisplay(uploadMode);

            if (uploadMode === 'local') {
                $('#video-storage-name').val(url);
                $('#video-url').val('');
            } else {
                $('#video-url').val(url);
                $('#video-storage-name').val('');
            }

            if (subcategory) {
                $('#video-category1').val(subcategory.categoryId);
                loadSubcategories(subcategory.categoryId);
                setTimeout(() => {
                    $('#video-category2').val(subcategoryId);
                }, 100);
            } else {
                $('#video-category1').val('');
                $('#video-category2').html('<option value="">请先选择一级分类</option>');
            }

            $('#video-modal').modal('show');
        });

        // 上传模式切换事件
        $('input[name="uploadModeRadio"]').change(function() {
            const mode = $(this).val();
            $('#video-upload-mode').val(mode);
            updateUploadModeDisplay(mode);

            // 清空相关字段
            if (mode === 'local') {
                $('#video-url').val('');
                $('#video-file').val('');
                $('#video-upload-progress').hide();
                $('#video-upload-status').text('');
                $('#video-storage-name').val('');
            } else {
                $('#video-storage-name').val('');
                $('#video-submit-btn').prop('disabled', false);
            }
        });

        // 视频文件选择事件 - 自动开始上传
        $('#video-file').change(function() {
            const file = this.files[0];
            if (file) {
                // 重置状态
                selectedVideoFile = file;
                videoFileMd5 = null;
                $('#video-upload-progress').hide();
                $('#video-upload-status').text('文件已选择，点击保存后开始上传');
                $('#video-storage-name').val('');

                // 检查文件名是否已存在
                checkFileNameExists(file.name);
            }
        });

        // 检查文件名是否已存在
        function checkFileNameExists(fileName) {
            // 这里需要调用后端接口检查文件名是否存在
            // 由于没有现成的接口，我们可以先模拟这个功能
            // 实际开发中需要添加后端接口来检查文件名

            $.get('/admin/video/check-filename', { fileName: fileName })
                .done(function(response) {
                    if (response.exists) {
                        $('#video-upload-status').text('错误：已存在相同文件名的视频，请勿重复上传');
                        $('#video-submit-btn').prop('disabled', true);
                        selectedVideoFile = null;
                        $('#video-file').val('');
                        showToast('error', '已存在相同文件名的视频，请勿重复上传');
                    } else {
                        $('#video-upload-status').text('文件已选择，点击保存后开始上传');
                        $('#video-submit-btn').prop('disabled', false);
                    }
                })
                .fail(function() {
                    // 如果检查接口失败，允许继续上传
                    $('#video-upload-status').text('文件已选择，点击保存后开始上传');
                    $('#video-submit-btn').prop('disabled', false);
                });
        }

// 修改表单提交验证
        $('#video-form').submit(function(e) {
            const uploadMode = $('#video-upload-mode').val();
            const url = $('#video-url').val();
            const storageName = $('#video-storage-name').val();

            if (uploadMode === 'network' && !url) {
                e.preventDefault();
                showToast('error', '请输入视频链接');
                return false;
            }

            if (uploadMode === 'local') {
                if (!selectedVideoFile) {
                    e.preventDefault();
                    showToast('error', '请选择视频文件');
                    return false;
                }

                if (!storageName) {
                    // 阻止默认提交，先上传文件
                    e.preventDefault();
                    uploadVideoFile(selectedVideoFile);
                    return false;
                }
            }

            if (uploadMode === 'server' && !url) {
                e.preventDefault();
                showToast('error', '请输入服务器文件路径');
                return false;
            }

            // 显示加载状态
            const formId = $(this).attr('id');
            $(`#${formId} .loading`).removeClass('d-none');
            $(`#${formId} .btn-primary`).prop('disabled', true);

            return true;
        });

        // 确认删除
        $('#confirm-delete').click(function () {
            let url = '';

            switch (currentDeleteType) {
                case 'category1':
                    url = '/admin/video/delete/one/' + currentDeleteId;
                    break;
                case 'category2':
                    url = '/admin/video/delete/two/' + currentDeleteId;
                    break;
                case 'video':
                    url = '/admin/video/delete/' + currentDeleteId;
                    break;
            }

            // 创建表单并提交
            const form = $('<form>', {
                'method': 'post',
                'action': url
            });
            $('body').append(form);
            form.submit();
        });

        // 一级分类变化时更新二级分类
        $('#video-category1, #category2-parent').change(function () {
            const categoryId = $(this).val();
            const targetId = $(this).attr('id') === 'video-category1' ? 'video-category2' : 'category2-id';
            loadSubcategories(categoryId, targetId);
        });

        // 表单提交前显示加载状态
        $('#category1-form, #category2-form').submit(function () {
            const formId = $(this).attr('id');
            $(`#${formId} .loading`).removeClass('d-none');
            $(`#${formId} .btn-primary`).prop('disabled', true);
            return true;
        });
    }

    // 更新上传模式显示
    function updateUploadModeDisplay(mode) {
        if (mode === 'local') {
            $('#video-url-container').hide();
            $('#video-file-container').show();
            $('#video-url').removeAttr('required');
            $('#video-file').attr('required', 'required');
        } else {
            $('#video-url-container').show();
            $('#video-file-container').hide();
            $('#video-file').removeAttr('required');
            $('#video-url').attr('required', 'required');

            if (mode === 'network') {
                $('#video-url').attr('placeholder', '请输入视频链接');
            } else {
                $('#video-url').attr('placeholder', '请输入服务器文件路径');
            }
        }
    }

    // 视频上传相关变量
    let videoUploadQueue = [];
    let currentVideoUpload = null;
    // 视频上传相关变量
    let selectedVideoFile = null;
    let videoFileMd5 = null;

    // 分片上传视频文件（在保存时调用）
    function uploadVideoFile(file) {
        const chunkSize = 5 * 1024 * 1024; // 5MB
        const totalChunks = Math.ceil(file.size / chunkSize);

        $('#video-upload-progress').show();
        $('#video-upload-status').text('开始上传...');
        $('#video-submit-btn').prop('disabled', true);

        // 生成文件MD5
        generateFileMd5(file).then(fileMd5 => {
            videoFileMd5 = fileMd5;
            // 检查已上传的分片
            checkVideoUploadedChunks(fileMd5, file, totalChunks);
        }).catch(error => {
            console.error('MD5生成失败:', error);
            $('#video-upload-status').text('文件处理失败');
            $('#video-submit-btn').prop('disabled', false);
            showToast('error', '文件处理失败');
        });
    }


    // 修复MD5生成函数
    async function generateFileMd5(file) {
        return new Promise((resolve) => {
            // 使用更安全的方式生成文件标识
            const reader = new FileReader();

            reader.onload = function(e) {
                // 使用文件的二进制数据生成哈希
                const buffer = e.target.result;
                const wordArray = CryptoJS.lib.WordArray.create(buffer);
                const hash = CryptoJS.MD5(wordArray).toString();
                resolve(hash);
            };

            reader.onerror = function() {
                // 如果读取失败，使用备用方案
                const backupHash = CryptoJS.MD5(
                    file.name + file.size + file.lastModified + Date.now()
                ).toString();
                resolve(backupHash);
            };

            // 只读取文件的一部分来生成MD5，提高性能
            const slice = file.slice(0, Math.min(file.size, 65536)); // 最多读取64KB
            reader.readAsArrayBuffer(slice);
        });
    }

    // 如果没有CryptoJS，使用简单的备用方案
    if (typeof CryptoJS === 'undefined') {
        window.CryptoJS = {
            lib: {
                WordArray: {
                    create: function(arr) {
                        return { words: Array.from(new Uint8Array(arr)) };
                    }
                }
            },
            MD5: function(wordArray) {
                // 简单的MD5模拟（实际应该使用完整的MD5实现）
                const simpleHash = function(str) {
                    let hash = 0;
                    for (let i = 0; i < str.length; i++) {
                        const char = str.charCodeAt(i);
                        hash = ((hash << 5) - hash) + char;
                        hash = hash & hash;
                    }
                    return Math.abs(hash).toString(16);
                };

                const data = wordArray.words.map(b => String.fromCharCode(b)).join('');
                return {
                    toString: () => simpleHash(data + Date.now())
                };
            }
        };
    }

    // 检查已上传的分片
    function checkVideoUploadedChunks(fileMd5, file, totalChunks) {
        $.get('/admin/video/chunks', { fileMd5: fileMd5 })
            .done(function(response) {
                const uploadedChunks = response.uploadedChunks || [];
                uploadVideoChunks(file, fileMd5, uploadedChunks, totalChunks);
            })
            .fail(function() {
                uploadVideoChunks(file, fileMd5, [], totalChunks);
            });
    }


    // 上传分片
    function uploadVideoChunks(file, fileMd5, uploadedChunks, totalChunks) {
        const chunkSize = 5 * 1024 * 1024;
        let currentChunk = 0;

        function uploadNextChunk() {
            // 跳过已上传的分片
            while (uploadedChunks.includes(currentChunk) && currentChunk < totalChunks) {
                currentChunk++;
            }

            if (currentChunk >= totalChunks) {
                // 所有分片上传完成，合并文件
                mergeVideoChunks(file, fileMd5);
                return;
            }

            const start = currentChunk * chunkSize;
            const end = Math.min(start + chunkSize, file.size);
            const chunk = file.slice(start, end);

            const formData = new FormData();
            formData.append('file', chunk);
            formData.append('fileMd5', fileMd5);
            formData.append('chunkIndex', currentChunk);
            formData.append('totalChunks', totalChunks);

            $('#video-upload-status').text(`上传中... ${currentChunk + 1}/${totalChunks}`);

            $.ajax({
                url: '/admin/video/upload/chunk',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        const progress = ((currentChunk + 1) / totalChunks) * 100;
                        $('#video-upload-progress .progress-bar').css('width', progress + '%').text(progress.toFixed(1) + '%');

                        currentChunk++;
                        uploadNextChunk();
                    } else {
                        $('#video-upload-status').text('上传失败: ' + response.message);
                        $('#video-submit-btn').prop('disabled', false);
                        showToast('error', '上传失败: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    $('#video-upload-status').text('上传失败: ' + (xhr.responseJSON?.message || error));
                    $('#video-submit-btn').prop('disabled', false);
                    showToast('error', '上传失败: ' + (xhr.responseJSON?.message || error));
                }
            });
        }

        uploadNextChunk();
    }


    // 合并分片
    function mergeVideoChunks(file, fileMd5) {
        $('#video-upload-status').text('文件合并中...');

        $.post('/admin/video/merge', {
            fileMd5: fileMd5,
            fileName: file.name,
            fileType: file.type || 'video/mp4',
            fileSize: file.size
        })
            .done(function(response) {
                if (response.success) {
                    $('#video-upload-status').text('上传成功');
                    $('#video-storage-name').val(response.storageName);
                    $('#video-submit-btn').prop('disabled', false);
                    showToast('success', '视频文件上传成功');

                    // 文件上传合并成功后，自动提交表单
                    setTimeout(() => {
                        $('#video-form').off('submit').submit();
                    }, 500);
                } else {
                    $('#video-upload-status').text('合并失败: ' + response.message);
                    $('#video-submit-btn').prop('disabled', false);
                    showToast('error', '视频文件合并失败: ' + response.message);
                }
            })
            .fail(function(xhr, status, error) {
                $('#video-upload-status').text('合并失败: ' + (xhr.responseJSON?.message || error));
                $('#video-submit-btn').prop('disabled', false);
                showToast('error', '视频文件合并失败');
            });
    }

    // 根据一级分类加载二级分类
    function loadSubcategories(categoryId, targetId = 'video-category2') {
        if (!categoryId) {
            $(`#${targetId}`).html('<option value="">请先选择一级分类</option>');
            return;
        }

        // 过滤出该一级分类下的二级分类
        const subcategories = category2Data.filter(item => item.categoryId == categoryId);

        let options = '<option value="">请选择二级分类</option>';
        subcategories.forEach(sub => {
            options += `<option value="${sub.id}">${sub.name}</option>`;
        });

        $(`#${targetId}`).html(options);
    }

    // 显示Toast消息函数
    function showToast(type, message) {
        // 创建Toast容器（如果不存在）
        let toastContainer = document.getElementById('toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.id = 'toast-container';
            toastContainer.className = 'position-fixed top-0 end-0 p-3';
            toastContainer.style.zIndex = '9999';
            document.body.appendChild(toastContainer);
        }

        // 创建Toast元素
        const toastId = 'toast-' + Date.now();
        const toastHtml = `
        <div id="${toastId}" class="toast align-items-center text-white bg-${type === 'success' ? 'success' : 'danger'} border-0" role="alert">
            <div class="d-flex">
                <div class="toast-body">
                    <i class="fa ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'} me-2"></i>
                    ${message}
                </div>
                <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
            </div>
        </div>
    `;

        toastContainer.insertAdjacentHTML('beforeend', toastHtml);

        // 显示Toast
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement);
        toast.show();

        // 自动移除Toast
        toastElement.addEventListener('hidden.bs.toast', function () {
            this.remove();
        });
    }

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';

        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));

        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
</script>
</body>
</html>